package com.apes.fn.scm.retailOrder.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.Objects;
import java.util.Optional;

/**
 * @author wuq
 * @create 2020-12-18 10:43
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = RetailPayMethodItem.CONST_TABLE_NAME)
public class RetailPayMethodItem extends BaseModel {

    public static final String CONST_TABLE_NAME = "Retail_Payment_Method_item";

    @Id
    @Column(name = "id")
    @Comment("收款方式明细编码")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "收款方式", prefix = "ZI")
    private String id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "retail_Payment_id", referencedColumnName = "id", nullable = false)
    private RetailOrderPayMethod retailOrderPayMethod;

    @Comment("收款金额")
    @Column(name = "amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double amount = 0;

    @Comment("部门编码")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    private Dept dept;

    @Comment("公司编码")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private PartyRole company;

    @Comment("零售单编码")
    @Column(name = "retail_Order_id", nullable = false)
    private String retailOrderId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "vip_Alliance", referencedColumnName = "id")
    private Enumeration vipAlliance; //会员联盟

    @Column(name = "platform_Discount_Flag", nullable = false, columnDefinition = "number(1,0) default 0")
    @Comment("平台折扣标记")
    private boolean platformDiscountFlag = false;

    public void setDept(Dept dept) {
        Optional.ofNullable(dept).orElseThrow( () -> new RuntimeException("传入的零售折扣明细存在部门为空，请检查！"));
        this.dept = dept;
        if (!Objects.isNull(dept)) {
            this.company = dept.getCompany();
        }
    }
}
